<?php


namespace App\Admin\Services\Wechat;


use App\Admin\Exceptions\Wechat\MiniProgramDraftException;
use App\Admin\Requests\Wechat\MiniProgramDraftToTemplateRequest;
use App\Models\Wechat\MiniProgramDraftToTemplateRecord;
use App\Repositories\Wechat\MiniProgramDraftToTemplateRecordRepository;
use Illuminate\Http\Request;

class MiniProgramDraftService {

    //代码草稿上传模板数量限制
    const DRAFT_TO_TEMPLATE_LIMIT = 45;

    /**
     * 代码草稿分页列表
     *
     * @param Request $request
     * @return array
     */
    public function page(Request $request) {
        $pageInfo        = $request->post('page_info');
        $miniProgramTool = new CompanyMiniProgramService();
        $draftList       = $miniProgramTool->getDraftsList();
        $result          = [
            'total_count' => 0,
            'list'        => []
        ];
        if (!empty($draftList)) {
            $draftCount = count($draftList);
            //根据创建时间降序排序
            foreach ($draftList as &$val) {
                $edition[]          = $val['create_time'];
                $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
            }
            array_multisort($edition, SORT_DESC, $draftList);
            //分页
            $draftListChunk = array_chunk($draftList, $pageInfo['per_page']);
            $result         = [
                'total_count' => $draftCount,
                'list'        => $draftListChunk[$pageInfo['page'] - 1]
            ];
        }
        return $result;
    }

    /**
     * 代码草稿添加至代码模板库
     *
     * @param MiniProgramDraftToTemplateRequest $request
     * @return \App\Commons\Utils\ModelTools\BaseModel|null
     * @throws MiniProgramDraftException
     */
    public function miniProgramDraftToTemplate(MiniProgramDraftToTemplateRequest $request) {
        $data            = $request->post();
        $miniProgramTool = new CompanyMiniProgramService();
        //判断线上模板库数量，最多45个
        $wxTemplateList = $miniProgramTool->getTemplateList();
        if (count($wxTemplateList) >= self::DRAFT_TO_TEMPLATE_LIMIT) {
            throw new MiniProgramDraftException(1100001);
        }
        //代码草稿添加至代码模板库
        $res = $miniProgramTool->createTemplateCreateFromDraft($data['draft_id']);
        //保存到mini_program_draft_to_template_records表
        $requestResult = ($res['errcode'] == 0 && $res['errmsg'] == 'ok') ?
            MiniProgramDraftToTemplateRecord::REQUEST_RESULT_SUCCESS :
            MiniProgramDraftToTemplateRecord::REQUEST_RESULT_FAIL;
        $recordData    = [
            'create_time'       => $data['create_time'],
            'user_version'      => $data['user_version'],
            'user_desc'         => $data['user_desc'],
            'wx_draft_id'       => $data['draft_id'],
            'user_id'           => $request->user()->id,
            'wx_request_result' => $requestResult,
            'remark'            => '',
        ];
        $fillAble      = array_keys($recordData);
        $recordRep     = new MiniProgramDraftToTemplateRecordRepository();
        $recordEl      = $recordRep->getEloquent()->fillable($fillAble)->fill($recordData);
        $recordEl->save();
        return $recordEl;
    }
}